﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace MQCommonLib
{
    public class MQHelper
    {
        private string _host;
        private string _user;
        private string _pwd;
        private string _exchange;

        public MQHelper() : this("localhost", "wjz001", "wjz", "sendmessage")
        {

        }

        public MQHelper(string host,
            string user,
            string pwd,
            string exchange)
        {
            if (string.IsNullOrEmpty(host))
            {
                throw new ArgumentNullException("host is not");
            }
            if (string.IsNullOrEmpty(user))
            {
                throw new ArgumentNullException("user is not");
            }
            if (string.IsNullOrEmpty(pwd))
            {
                throw new ArgumentNullException("pwd is not");
            }
            if (string.IsNullOrEmpty(exchange))
            {
                _exchange = "sendmessage";
            }
            else
            {
                _exchange = exchange;
            }


            _host = host;
            _user = user;
            _pwd = pwd;

            createFac();
        }


        private ConnectionFactory _ConnectionFactory;
        private void createFac()
        {
            _ConnectionFactory = new ConnectionFactory();
            _ConnectionFactory.HostName = _host;
            _ConnectionFactory.Password = _pwd;
            _ConnectionFactory.UserName = _user;

        }

        public void SendMessage(byte[] message)
        {
            using (var connect = _ConnectionFactory.CreateConnection())
            {
                using (var channel = connect.CreateModel())
                {
                    channel.QueueDeclare(_exchange, false, false, false, null);

                    channel.BasicPublish("", _exchange, null, message);
                }
            }
        }

        public void GetMessage()
        {
            using (var connect = _ConnectionFactory.CreateConnection())
            {
                using (var channel = connect.CreateModel())
                {
                    channel.QueueDeclare(_exchange, false, false, false, null);

                    while (true)
                    {
                        var consumer = new EventingBasicConsumer(channel);
                        channel.BasicConsume(_exchange, false, consumer);
                        consumer.Received += (m, e) =>
                        {
                            var body = e.Body.ToArray();
                            var message = System.Text.UTF8Encoding.UTF8.GetString(body);

                            Console.WriteLine("服务端接收到信息: " + message);
                        };

                        System.Threading.Thread.Sleep(100);
                    }
                }
            }

        }
    }
}
